<template>
  <div ref="chart" :style="chartStyle"></div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "echartWrap",
  props: {
    // options: {
    //   type: Object,
    //   required: true
    // },
    height: {
      type: String,
      default: "300px"
    },
    width: {
      type: String,
      default: "100%"
    }
  },
  data() {
    return {
      chart: null, // 这里声明了图表实例的变量

      options: {}
    };
  },
  computed: {
    chartStyle() {
      return {
        height: this.height,
        width: this.width,
        background: "whitesmoke"
      };
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart(); // 这里初始化图表
      window.addEventListener("resize", this.resizeChart);
      this.init();
    });
  },
  beforeDestroy() {
    if (this.chart) {
      window.removeEventListener("resize", this.resizeChart);
      this.chart.dispose();
    }
  },
  methods: {
    initChart() {
      const chartDom = this.$refs.chart;
      this.chart = echarts.init(chartDom); // 这里创建了一个ECharts图表实例
      this.chart.setOption(this.options);
    },
    resizeChart() {
      if (this.chart) {
        this.chart.resize();
      }
    },
    init() {
      var today = new Date();
      // 将今天的日期的时间设置为0点0分0秒
      var minDate = new Date(
        today.getFullYear(),
        today.getMonth(),
        today.getDate(),
        0,
        0,
        0
      );
      // 将今天的日期的时间设置为23点59分59秒
      var maxDate = new Date(
        today.getFullYear(),
        today.getMonth(),
        today.getDate(),
        23,
        59,
        59
      );
      var newOption = {
        title: {
          text: "2024-04-07 任务情况"
        },
        legend: {
          data: ["任务时长"],
          // 设置图例组件的布局方向
          orient: "vertical",
          // 设置图例组件的位置
          right: 10,
          top: 20,
          bottom: 20,
          height: "auto",
          type: "plain"
        },
        tooltip: {
          trigger: "item",
          formatter: function(params) {
            // console.log(params)
            return (
              params.seriesName +
              "<br/>开始时间: " +
              params.data[1] +
              "<br/>结束时间: " +
              params.data[2]
            );
          }
        },
        grid: {
          top: "20%",
          left: "15%",
          right: "30%",
          bottom: "15%",
          containLabel: true
        },
        xAxis: {
          type: "time",
          min: minDate.getTime(), // 设置x轴最小值为今天0点
          max: maxDate.getTime(), // 设置x轴最大值为今天23点59分59秒
          axisLabel: {
            formatter: "{HH}:{mm}:{ss}" // 得到的 label 形如：'2020-12-02'
          }
        },
        yAxis: {
          type: "category",
          data: ["2024-04-07", "2024-04-08", "2024-04-09", "2024-04-10"]
        },
        series: [
          {
            name: "任务时长",
            type: "custom",
            renderItem: function(params, api) {
              var categoryIndex = api.value(0);
              var start = api.coord([api.value(1), categoryIndex]);
              var end = api.coord([api.value(2), categoryIndex]);
              var height = api.size([0, 1])[1] * 0.6;

              return {
                type: "rect",
                shape: echarts.graphic.clipRectByRect(
                  {
                    x: start[0],
                    y: start[1] - height / 2,
                    width: end[0] - start[0],
                    height: height
                  },
                  {
                    x: params.coordSys.x,
                    y: params.coordSys.y,
                    width: params.coordSys.width,
                    height: params.coordSys.height
                  }
                ),
                style: api.style()
              };
            },
            encode: {
              x: [1, 2], // 表示维度 3、1、5 映射到 x 轴。
              y: 0 // 表示维度 2 映射到 y 轴。
            },
            data: [
              // Format: [yAxis index, task start, task end]
              // Example: [0, start hour, end hour]
              [0, "2024-04-07 08:09:10", "2024-04-07 09:09:10"], // Task 1
              [0, "2024-04-07 18:09:10", "2024-04-07 19:09:10"] // Task 1
            ],
            label: {
              show: true,
              position: "insideRight"
            }
          },
          {
            name: "任务时长2",
            type: "custom",
            renderItem: function(params, api) {
              var categoryIndex = api.value(0);
              var start = api.coord([api.value(1), categoryIndex]);
              var end = api.coord([api.value(2), categoryIndex]);
              var height = api.size([0, 1])[1] * 0.6;

              return {
                type: "rect",
                shape: echarts.graphic.clipRectByRect(
                  {
                    x: start[0],
                    y: start[1] - height / 2,
                    width: end[0] - start[0],
                    height: height
                  },
                  {
                    x: params.coordSys.x,
                    y: params.coordSys.y,
                    width: params.coordSys.width,
                    height: params.coordSys.height
                  }
                ),
                style: api.style({ fill: api.value(3) })
              };
            },
            encode: {
              x: [1, 2], // 表示维度 3、1、5 映射到 x 轴。
              y: 0 // 表示维度 2 映射到 y 轴。
            },
            data: [
              // Format: [yAxis index, task start, task end]
              // Example: [0, start hour, end hour]
              [1, "2024-04-07 08:09:10", "2024-04-07 13:14:10", "#0000cd"], // Task 1
              [1, "2024-04-07 18:09:10", "2024-04-07 19:09:10", "#0cd0cd"] // Task 1
            ]
          }
        ],
        dataZoom: [
          {
            type: "slider", // 这是滑块型数据缩放组件
            xAxisIndex: 0, // 表示这个 dataZoom 组件控制着 xAxis 索引为 0 的轴
            start: 0, // 数据窗口范围的起始百分比, 表示一开始展示全部数据
            end: 100,
            filterMode: "weakFilter", // 数据窗口范围的结束百分比,
            labelFormatter: function(value) {
              const date = new Date(value);
              const hours = date.getHours();
              const minutes = date.getMinutes();
              const seconds = date.getSeconds();
              return `${hours}:${minutes}:${seconds}`;
            }
          },
          {
            type: "inside", // 这是内置型数据缩放组件
            xAxisIndex: 0,
            start: 0,
            end: 100,
            filterMode: "weakFilter" // 数据窗口范围的结束百分比
          }
        ]
      };

      this.chart.setOption(newOption, true);
    }
  },
  watch: {
    options: {
      handler(newOption) {
        if (this.chart) {
          this.chart.setOption(newOption, true);
        }
      },
      deep: true
    }
  }
};
</script>

<style scoped>
/* 可以根据需要添加样式 */
</style>
